package array;

public class 二分查找704 {

    public static int search(int[] nums, int target) {
        if (nums == null || nums.length == 0) {
            return -1;
        }

        // 避免当 target 小于nums[0] nums[nums.length - 1]时多次循环运算
        if (target < nums[0] || target > nums[nums.length - 1]) {
            return -1;
        }

        int left = 0;
        int right = nums.length - 1;

        while (left <= right) {
            int mid = left + ((right - left) / 2);
            if (nums[mid] > target) {
                // TODO target 在左区间，所以[left, middle - 1]
                right = mid - 1;
            } else if (nums[mid] < target) {
                // TODO target 在右区间，所以[middle + 1, right]
                left = mid + 1;
            } else if (nums[mid] == target) {
                return mid;
            }
        }

        return -1;
    }

    public static void main(String[] args) {
        int[] nums = {-1,0,3,5,9,12};
        int target = 9;
        System.out.println(search(nums, target));
    }
}
